#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <time.h>

void Write(int fd, const char* buf, size_t len) {
	int n = 0;
	while(len > 0) {
		n = write(fd, buf, len);
		if(n == 0) {
			printf("peer closed\n");
			return;
		}
		if(n < 0 && errno == EINTR) {
			continue;
		}
		len -= n;
	}
}

int main(int argc, char **argv) {
	int fd;
	struct sockaddr_in serv_addr;
	fd = socket(AF_INET, SOCK_STREAM, 0);
	memset(&serv_addr, 0, sizeof(struct sockaddr_in));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(6666);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	//if(bind(fd,(struct sockaddr*)&serv_addr, sizeof(serv_addr)) != 0) {
		//printf("bind addr error.errno=%d errmsg=%s\n", errno, strerror(errno));
		//return errno;
	//}
	listen(fd, 10);

	struct sockaddr_in client_addr;
	int client_fd;
	socklen_t addr_len = sizeof(client_addr);
	while((client_fd = accept(fd, (struct sockaddr*)&client_addr, &addr_len)) > 0) {
		if(client_addr.sin_family != AF_INET) {
			printf("only support IPv4\n");
			continue;
		}
		char ip[16];
		if(inet_ntop(AF_INET, &client_addr.sin_addr, ip, 16) == 0) {
			printf("parse client ip error\n");
			continue;
		}
		uint16_t port = ntohs(client_addr.sin_port);
		printf("accept client:[%s:%d]\n", ip, port);
		time_t t = time(NULL);
		char buff[1024];
		snprintf(buff,1024, "%.24s\r\n", ctime(&t));
		Write(client_fd, buff, strlen(buff));
		close(client_fd);
	}

	printf("accept error. errno=%d errmsg=%s\n", errno, strerror(errno));
	close(fd);

	return errno;
}

